package com.zzw.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzw.reggie.common.R;
import com.zzw.reggie.entity.User;
import com.zzw.reggie.service.IUserService;
import com.zzw.reggie.utils.SMSUtils;
import com.zzw.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private IUserService userService;

    /**
     * 发送验证码
     *
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        //获取手机号
        String phone = user.getPhone();
        //判断手机号是否为空
        if (StringUtils.hasText(phone)) {
            //生成验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("验证码为：{}",code);
            //调用阿里云的发送验证码API
            //SMSUtils.sendMessage("朱志威的博客", "SMS_463780621", phone, code);
            //将验证码存储起来
            session.setAttribute(phone, code);
            return R.success("验证码发送成功");
        }

        return R.error("验证码发送失败");
    }

    /**
     * 登录方法
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session) {
        log.info(map.toString());

        //获取手机号
        String phone = map.get("phone").toString();
        //获取验证码
        String code = map.get("code").toString();
        //从session中获取发送的验证码
        String codeInSession = session.getAttribute(phone).toString();
        //进行验证码比对（页面提交的验证码和发送的验证码）
        if (StringUtils.hasText(code) && codeInSession.equals(code)) {
            //比对成功 登录成功

            //判断当前手机号是否为新用户 如果是新用户自动完成注册
            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
            lqw.eq(User::getPhone,phone);
            User user = userService.getOne(lqw);
            if (user == null){
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }

            //登录成功 将数据存放到session中
            session.setAttribute("user",user.getId());
            return R.success(user);
        }


        return R.error("登录失败");
    }
}
